import axios from 'axios'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'

const $axios = axios.create({
  baseURL: `${import.meta.env.VITE_BASE_API}`,
  timeout: 10000,
})

$axios.interceptors.request.use(config => {
  const { token = '' } = useUserStore()
  config.headers.token = token
  return config
})

$axios.interceptors.response.use(response => {
  return response.data
}, err => {
  let msg = ''
  let status = err.response.status
  switch (status) {
    case 401:
      msg = 'token 过期'
      break;
    case 403:
      msg = '无访问权限'
      break;
    case 404:
      msg = '访问路径错误'
      break;
    case 500:
      msg = '服务器错误'
      break;
    default:
      msg = '未知错误'
      break;
  }
  ElMessage.error({
    type: 'error',
    message: msg
  })
  return Promise.reject(err)
})

export default $axios